package mju.cxf.interceptor;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import mju.cxf.constant.JwtClaimsConstant;
import mju.cxf.context.BaseContext;
import mju.cxf.properties.JwtProperties;
import mju.cxf.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getJwtTokenName());
        if (token==null){
            //没有token 响应401
            response.setStatus(401);
            return false;
        }
        //2、校验令牌
        try {
//            log.info("jwt校验:{}", token);
            String uri = request.getRequestURI();
            String uriRole = uri.split("/")[1];
            Claims claims = JwtUtil.parseJWT(jwtProperties.getJwtSecretKey(),token);
            //判定角色
            String role = claims.get(JwtClaimsConstant.ROLE).toString();
            if (!(uriRole.equalsIgnoreCase(role))){
                //没有对应角色权限权限返回403状态码
                response.setStatus(403);
                return false;
            }
            int userId = Integer.parseInt(claims.get(JwtClaimsConstant.JWT_ID).toString());
            BaseContext.setCurrentId(userId);
//            log.info("当前登陆用户id：{}", userId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //过期token，响应401状态码 禁止访问
            response.setStatus(401);
            return false;
        }
    }
}
